package com.google.code.jtasks.query;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.joda.time.DateTime;

import com.google.code.jtasks.model.IMappedTask;
import com.google.code.jtasks.model.TaskId;

/**
 * Used to hold the {@link IMappedTask}s returned by a {@link TaskQuery}.
 */
public class TaskQueryResult
{
	private final List<IMappedTask> tasks;

	/**
	 * Constructs a new {@link TaskQueryResult} instance.
	 * 
	 * @param tasks
	 *            the {@link IMappedTask}s that were returned by the {@link TaskQuery}
	 */
	public TaskQueryResult(IMappedTask... tasks)
	{
		this(Arrays.asList(tasks));
	}

	/**
	 * Constructs a new {@link TaskQueryResult} instance.
	 * 
	 * @param tasks
	 *            the {@link List} of {@link IMappedTask}s that were returned by the {@link TaskQuery}
	 */
	public TaskQueryResult(List<IMappedTask> tasks)
	{
		if (tasks == null)
			throw new IllegalArgumentException("Null task list result not allowed.");

		this.tasks = new ArrayList<IMappedTask>(tasks);
	}

	/**
	 * Returns the first {@link IMappedTask} returned by the {@link TaskQueryResult}, or <code>null</code> if
	 * no {@link IMappedTask}s were found.
	 * 
	 * @return the first {@link IMappedTask} returned by the {@link TaskQueryResult}, or <code>null</code> if
	 *         no {@link IMappedTask}s were found
	 */
	public IMappedTask getTask()
	{
		return tasks.isEmpty() ? null : tasks.get(0);
	}

	/**
	 * Returns the first {@link IMappedTask} returned by the {@link TaskQueryResult} that matches the
	 * specified criteria, or <code>null</code> if matching {@link IMappedTask}s were found.
	 * 
	 * @param id
	 *            the {@link TaskId} of the {@link IMappedTask} to search for
	 * @return the first {@link IMappedTask} returned by the {@link TaskQueryResult} that matches the
	 *         specified criteria, or <code>null</code> if matching {@link IMappedTask}s were found
	 */
	public IMappedTask getTask(TaskId id)
	{
		// Sanity checks...
		if (id == null)
			throw new IllegalArgumentException("null ID");
		if (tasks.isEmpty())
			return null;

		// Try to find a matching task
		for (IMappedTask task : tasks)
			if (task.getId().equals(id))
				return task;

		// No match found, return null
		return null;
	}

	/**
	 * Returns the {@link List} of {@link IMappedTask}s that were returned by the {@link TaskQuery}.
	 * 
	 * @return the {@link List} of {@link IMappedTask}s that were returned by the {@link TaskQuery}
	 */
	public List<IMappedTask> getTasks()
	{
		return Collections.unmodifiableList(tasks);
	}

	public DateTime getTimestamp()
	{
		// TODO Auto-generated method stub
		return null;
	}
}
